package com.supermap.agricultural_meteoro.monitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.supermap.agricultural_meteoro.monitor.util.ImageUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "file")
public class  FileController {

    @RequestMapping(value = "test")
    @ResponseBody
    public String home() {
        return "File Upload";
    }

    @RequestMapping(value = "singleUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("img") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return "ERROR";
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            return "ERROR";
        }

        String filePath = "/root/img";

        try {
            String fileName = ImageUtil.saveImg(multipartFile, filePath);
            return fileName;
        } catch (IOException e) {
            return "ERROR";
        }
    }

    @RequestMapping(value = "multiUpload")
    @ResponseBody
    public String multiFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        boolean flag = true;
        int count = 0;
        while (flag) {
            String img = "img" + count;
            List<MultipartFile> tmpFiles = ((MultipartHttpServletRequest) request).getFiles(img);
            if (tmpFiles != null && tmpFiles.size() > 0) {
                files.addAll(tmpFiles);
                count ++;
            } else {
                flag = false;
            }
        }
        JSONObject result = new JSONObject();
        List<String> images = new ArrayList<String>();
        String img;
        for (MultipartFile file : files) {
            img = uploadFile(file);
            if (img != null) {
                images.add(img);
            }
        }
        result.put("data", images);
        return result.toJSONString();
    }

    private String uploadFile(MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return "ERROR";
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            return "ERROR";
        }

        String filePath = "./img";

        try {
            String fileName = ImageUtil.saveImg(multipartFile, filePath);
            return fileName;
        } catch (IOException e) {
            return "ERROR";
        }
    }
}
